// ! 调用 listenMsg 会返回一个'关闭监听'的函数，页面卸载时一定要调用此函数，否则会造成重复监听
type FnType<T = any> = [(data: T) => void, (cb: (data: T) => void) => () => void];
export function createCrossTagMsg<DataT = any>(name: string): FnType<DataT> {
	const channel = new BroadcastChannel(name);

	function sendMsg(data: DataT) {
		channel.postMessage(data);
	}

	function listenMsg(callback: (data: DataT) => void) {
		const handler = (event: MessageEvent) => {
			callback?.(event.data);
		};

		channel.addEventListener('message', handler);
		// channel.onmessage = handler;

		return () => {
			channel.removeEventListener('message', handler);
			// channel.close();
		};
	}

	return [sendMsg, listenMsg];
}
